from django.core.cache import cache
from django.utils import timezone
from django.db import transaction
from .models import Visitor, BrowseRecord


@transaction.atomic
class VisitorMiddleware:
    def process_view(self, request, view_func, view_args, view_kwargs):
        if hasattr(view_func, '__name__') and view_func.__name__ in {'home', 'get_detail', 'get_tag_list',
                                                                     'get_archive_list',
                                                                     'get_catagory_list', 'alipay', 'resume'}:
            ip = request.META['HTTP_X_FORWARDED_FOR'] if 'HTTP_X_FORWARDED_FOR' in request.META else request.META[
                'REMOTE_ADDR']

            visitor = Visitor.get_visitor(ip)

            online_ips = cache.get("online_ips", [])

            if online_ips:
                online_ips = list(cache.get_many(online_ips).keys())

            cache.set(ip, 0, 5 * 60)

            if ip not in online_ips:
                online_ips.append(ip)

            cache.set("online_ips", online_ips)

            visitor.date_time = timezone.now()
            visitor.save()
            browse_record = BrowseRecord(visitor=visitor)
            browse_record.save()
